package online.shiming.file.util;


import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import lombok.extern.slf4j.Slf4j;

/**
 * @author Ming
 */
@Component
@ServerEndpoint(value = "/fileWebsocket", encoders = WebSocketCustomEncoding.class)
@Slf4j
public class FileWebSocket {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static CopyOnWriteArraySet<FileWebSocket> webSocketSet = new CopyOnWriteArraySet<FileWebSocket>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //存储用户信息
        webSocketSet.add(this);
        Map<String, Object> map = new HashMap<>();
        map.put("fileSize", -1);
        map.put("percent", 0);
        sendMessage(map);
        System.out.println("连接成功");
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //从set中删除
        webSocketSet.remove(this);
        System.out.println("关闭连接");
    }

    public static void sendMessage(Map<String, Object> msg) {
        for (FileWebSocket webSocket : webSocketSet) {
            try {
                webSocket.session.getBasicRemote().sendObject(msg);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("发送失败");
            }
        }
    }

}